import axios from 'axios'
// import { Spin } from 'iview'
import { Modal } from 'iview'
class HttpRequest {
  constructor (baseUrl = baseURL) {
    this.baseUrl = baseUrl
    this.queue = {}
  }
  getInsideConfig () {
    const config = {
      baseURL: this.baseUrl,
      headers: {
        'Content-Type': 'application/json'
      }
      // 表示跨域请求时是否需要使用凭证，默认false
      // withCredentials: true
    }
    return config
  }
  destroy (url) {
    delete this.queue[url]
    if (!Object.keys(this.queue).length) {
      // Spin.hide()
    }
  }
  interceptors (instance, url) {
    // 请求拦截
    instance.interceptors.request.use(config => {
      // 添加全局的loading...
      if (!Object.keys(this.queue).length) {
        // Spin.show() // 不建议开启，因为界面不友好
      }
      this.queue[url] = true
      return config
    }, error => {
      return Promise.reject(error)
    })
    // 响应拦截
    instance.interceptors.response.use(res => {
      this.destroy(url)
      const { data, status } = res
      return { data, status }
    }, error => {
      this.destroy(url)
      if (error.response) {
        switch (error.response.status) {
          case 401:
            let seconds = 5
            // 返回 401 重定向到登录页面
            Modal.warning({
              title: '登录超时',
              content: '<p>由于您长时间没有操作，登录超时，</p><p> <span id="stimeout">5</span> 秒后将重定向到登录页面重新登录！</p>',
              maskClosable: false,
              closable: false,
              okText: '立即跳转',
              onOk: () => {
                window.location.href = '//nslab.dgut.edu.cn'
                Modal.remove()
              }
            })
            let timer = setInterval(() => {
              document.querySelector('#stimeout').innerHTML = --seconds
              if (seconds <= 0) {
                clearInterval(timer)
                window.location.href = '//nslab.dgut.edu.cn'
                Modal.remove()
              }
            }, 1000)
        }
      }
      return Promise.reject(error)
    })
  }
  request (options) {
    const instance = axios.create()
    options = Object.assign(this.getInsideConfig(), options)
    this.interceptors(instance, options.url)
    return instance(options)
  }
}
export default HttpRequest
